package com.tianxiao.test.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.baijia.tianxiao.sqlbuilder.SingleSqlBuilder;
import com.baijia.tianxiao.sqlbuilder.support.JdbcTemplateDaoSupport;
import com.google.common.collect.Maps;
import com.tianxiao.test.dao.AreaDao;
import com.tianxiao.test.model.Area;

@Repository
public class AreaDaoImpl extends JdbcTemplateDaoSupport<Area> implements AreaDao {

    @Override
    public List<Area> getAreaByLevel(int level) {
        SingleSqlBuilder<Area> builder = createSqlBuilder();
        builder.eq("level", level);
        
        builder.desc("displayOrder");
        
        return queryList(builder);
    }

    @Override
    public List<Area> getSubAreaByIdAndMask(int areaId, int level, long mask) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("mask", mask);
        map.put("level", level);
        map.put("id", areaId);

        StringBuilder sb = new StringBuilder(
            "select id,name,level,bname from cdb.area where id&:mask = :id and level = :level order by display_order desc");
        return this.getNamedJdbcTemplate().query(sb.toString(), map, new RowMapper<Area>() {
            @Override
            public Area mapRow(ResultSet resultSet, int i) throws SQLException {

                Area area = new Area();
          
                area.setId(resultSet.getInt("id"));
                area.setName(resultSet.getString("name"));
                area.setBname(resultSet.getString("bname"));
                area.setLevel(resultSet.getInt("level"));
                return area;
            }
        });
    }

}
